<?php
/**
 * Description: 拉取中奖信息
 * Created by PhpStorm.
 * User: 玉坤
 * Date: 2021/6/15
 * Time: 18:06
 */

use Biz\model\NewProduct\NewProductJdCardModel;
use Biz\model\NewProduct\NewProductLotteryLogModel;
use Biz\model\NewProduct\NewProductWikiModel;
use Biz\model\NewProduct\NewProductWinnerListModel;
use Doraemon\cache\Queue;
use Doraemon\model\Sysmsg;
use Doraemon\tools\Hhzurl;
use Doraemon\tools\LinkFormat;
use Doraemon\service\User;

ini_set('display_errors', 1);
error_reporting(E_ALL ^ E_NOTICE ^ E_WARNING ^ E_DEPRECATED);
ini_set('memory_limit', '1024M');

require_once '/data/wwwroot/g_vendor/autoload.php';

$start = microtime(true);
$page = 1;
$pageSize = 50;
$lists = [];


do {
    $limit = [($page - 1) * $pageSize, $pageSize];
    $where = [
        'create_time[<=]' => date('Y-m-d H:i:s'),
        'create_time[>=]' => date('Y-m-d 00:00:00'),
        'get_data_status' => NewProductLotteryLogModel::GET_DATA_OFF,
        "LIMIT" => $limit,
    ];
    $lists = NewProductLotteryLogModel::select("*", $where);
    $jd_ids = [];
    foreach ($lists as $list) {
        try {
            $series_id = $list['series_id'];
            $prize_id = $list['prize_id'];
            $res = \Doraemon\service\Lottery\Lottery::getAwardUserList($series_id, $prize_id);
            if (!$res) {
                \Doraemon\tools\Log::info('未拉取到中奖信息', $list['nid']);
                continue;
            }
            $log['info'] = $list;
            $log['params'] = [
                $series_id,
                $prize_id,
            ];
            $log['res'] = $res;
            \Doraemon\tools\Log::info('拉取抽奖数据', $log);

            $uids = array_column($res['award_user_list'], 'uid');
            $data = [];
            if ($uids) {
                //查询是否是京东卡奖品
                if ((int)$list['type'] === NewProductWikiModel::GRACE_PDT) {
                    $jd_where['nid'] = $list['nid'];
                    $jd_where['is_used'] = NewProductJdCardModel::NO_USED;
                    $jd_card_list = NewProductJdCardModel::all($jd_where, ['jd_num', 'id']);
                } else {
                    $jd_card_list = [];
                }
                foreach ($uids as $k => $uid) {
                    $jd_ids[] = $jd_card_list[$k]['id'] ?? 0;
                    $data[$k]['uid'] = $uid ?? 0;
                    $data[$k]['jd_num'] = $jd_card_list[$k]['jd_num'] ?? '';
                    $data[$k]['basic_id'] = $list['basic_id'] ?? 0;
                    $data[$k]['nid'] = $list['nid'] ?? 0;
                    $data[$k]['type'] = $list['type'];
                    $data[$k]['prize_name'] = $res['prize_info']['prize_name'] ?: $list['name'];

                    $data[$k]['addtime'] = date('Y-m-d H:i:s');
                    $data[$k]['edittime'] = date('Y-m-d H:i:s');
                    if (isset($jd_card_list[$k]['jd_num']) && $jd_card_list[$k]['jd_num']) {
                        $data[$k]['winner_status'] = NewProductWinnerListModel::SEND_PRIZE;
                    } else {
                        $data[$k]['winner_status'] = NewProductWinnerListModel::NO_ADDRESS;
                    }
                }
            }


            //存储记录更新状态
            if ($data) {
                NewProductWinnerListModel::action(function () use ($jd_ids, $list, $data, &$result) {
                    $jd_ids = array_filter($jd_ids);
                    if ($jd_ids && is_array($jd_ids)) {
                        $result = NewProductJdCardModel::update(['is_used' => NewProductJdCardModel::USED], ['id' => $jd_ids, 'is_used' => NewProductJdCardModel::NO_USED]);
                            $sql_log = NewProductJdCardModel::log();
                            \Doraemon\tools\Log::error('更新京东卡状态sql:', compact('list', 'jd_ids', 'sql_log'));
                    }
                    $result = NewProductWinnerListModel::insert($data);
                    if ($result->rowCount() == 0) {
                        $sql_log = NewProductWinnerListModel::log();
                        \Doraemon\tools\Log::error('插入中奖数据失败:', compact('list', 'sql_log'));
                        return false;
                    }
                    $result = NewProductLotteryLogModel::update(
                        [
                            'get_data_status' => NewProductLotteryLogModel::GET_DATA_ON,
                            'update_time' => date('Y-m-d H:i:s')
                        ],
                        ['id' => $list['id']]
                    );
                    if ($result->rowCount() == 0) {
                        $sql_log = NewProductLotteryLogModel::log();
                        \Doraemon\tools\Log::error('插入中奖数据失败:', compact('list', 'sql_log'));
                        return false;
                    }
                });

                if ($result->rowCount()) {
                    //发送push 系统消息
                    SendNotice($data);
                } else {
                    \Doraemon\tools\Log::error('拉取中奖-回滚', $list);
                }
            }
        } catch (\Exception $e) {
            \Doraemon\tools\Log::error('拉取新品速度中将数据_error:' . $e->getMessage(), $lists);
            var_dump($e->getMessage());
        }
    }
    $page++;


} while ($lists);

$end = microtime(true);
$time = $end - $start;
$second = round($time, 3);
var_dump('完成时间：' . date('Y-m-d H:i:s') . '   总耗时:' . $second . '秒');


//$desc = '感谢参与「新品速递」活动，恭喜你抽中 '.$prize_info['prize_name'].' ，快来填写收货地址吧，我们将尽快为你寄出奖品';
//Hi {nickname}，感谢参与「新品速递」，恭喜你中奖了「50元京东卡」！快来领取你的兑换码吧～
//Hi {nickname}，感谢参与「新品速递」，恭喜你中奖了「50元京东卡」！快来填写收货地址吧，我们将尽快安排发货～


function SendNotice($data)
{
    \Doraemon\tools\Log::info('发送新品速递中奖-push/系统消息:', $data);

    $uids = array_column($data, 'uid');
    $user_info = User::getBatchBasicUserInfo($uids);
    $user_info = array_column($user_info, 'nick', 'uid');
    foreach ($data as $datum) {
        $nid = $datum['nid'];
        $link = Hhzurl::getDomain() . '/brand/new-product-express/product-lottery?nid=' . $nid . '&hhzjump=1';
        $link = LinkFormat::encryptionLink($link);
        $user_nick = $user_info[$datum['uid']] ?: '亲爱的住友';
        //超级新品-实物
        $desc = 'Hi ' . $user_nick . '，感谢参与「新品速递」活动，恭喜你抽中 ' . $datum['prize_name'] . ' ，快来填写收货地址吧，我们将尽快为你寄出奖品~';
        //甄选新品-jd卡
        if ((int)$datum['type'] === NewProductWikiModel::GRACE_PDT) {
            $desc = "Hi " . $user_nick . "，感谢参与「新品速递」活动，恭喜你抽中「50元京东卡」！快来填写收货地址吧，我们将尽快为你寄出奖品～";
            if ($datum['jd_num']) {
                $desc = "Hi " . $user_nick . "，感谢参与「新品速递」活动，恭喜你中奖了「50元京东卡」！快来领取你的兑换码吧～";
            }
        }
        $img = 'https://img.haohaozhu.cn/Biz-imageShow/o_phone/059/6708f30ku0af0dk00qwh8y5?w=1080&h=540&iv=1';
        systemMsg($desc, $datum['uid'], $link, $img);
        pushMsg($desc, $datum['uid'], $link, $img);
    }

}


//系统通知
function systemMsg($desc, $uid, $link, $img)
{
    if ($uid && $uid > 0) {
        $data = [
            'msgCode' => 0,
            'to_uid' => $uid,
            'msgParams' => [
                'from_uid' => '',
                'title' => '恭喜你中奖啦！',
                'detail' => $desc,
                'link' => $link,
                'type' => Sysmsg::TYPE_NOTICE,
                'img' => $img
            ],
        ];
        var_dump('系统消息');
        var_dump($data);
        Queue::insertQueue('queue/Sysmsg/Send', $data, Queue::QUEUE_DORAEMON);
    }
}

//push消息
function pushMsg($desc, $uid, $link, $img)
{
    if ($uid && $uid > 0) {
        $pushId = 'push_new_product_lottery_' . date('Y_m_d');
        $params = [
            'uid' => $uid,
            'title' => '恭喜你中奖啦！',
            'alert' => $desc,
            'param' => [
                'link' => $link,
                'push_id' => $pushId,
                'image' => $img
            ]
        ];
        var_dump('push消息');
        var_dump($params);
        \Doraemon\service\Push\PushService::send($params);
    }

}
